package com.paic.mhis.hcpms.quota.settlement.web.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.quota.exportword.biz.service.QueryWordWebPageService;
import com.paic.mhis.hcpms.quota.settlement.biz.service.KpiRegionCodeService;
import com.paic.mhis.hcpms.quota.settlement.common.Constants;
import com.paic.mhis.hcpms.quota.settlement.dto.MedOrgLevelDTO;
import com.paic.mhis.hcpms.quota.settlement.dto.WordInfoDTO;
import com.paic.mhis.hcpms.quota.settlement.web.vo.WordInfoVO;
import com.paic.pafa.appclient.annotation.BizServicesProxy;

@Controller
@RequestMapping("/report/")
public class QueryWordWebPageController {

	private static final Logger logger = Logger.getLogger(QueryWordWebPageController.class);

	@BizServicesProxy(beanName = "kpiRegionCodeService")
	public KpiRegionCodeService kpiRegionCodeService;

	@BizServicesProxy(beanName = "queryWordWebPageService")
	public QueryWordWebPageService queryWordWebPageService;

	@Value("${rtfFileDownloadPath}")
	public String rtfReportDir;

	/**
	 * @param request
	 * @return Map<String, Object> 查询word列表
	 */
	@RequestMapping("queryWordList.do")
	@ResponseBody
	public Map<String, Object> queryWordList(@RequestBody WordInfoVO wordParams, HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");
		String regionCode = this.kpiRegionCodeService.getRegionCode(user.getUserId());
		String msg = "";
		if (StringUtils.isBlank(regionCode)) {
			msg = "您没有指定统筹区域,请联系管理员,";
			resultMap.put("state", 1);
			resultMap.put("msg", msg);
			return resultMap;
		}
		// 获取查询条件 cate : 报告类型（月度报告） date : 统计日期(2015-02)
		// healthcareProviderCode
		// : 机构名称编码(厦门) orgLevel : 机构等级
		String cate = wordParams.getCate();// 13
		String date = wordParams.getDate();
		String healthcareProviderCode = wordParams.getHealthcareProviderCode();
		String orgLevel = wordParams.getOrgLevel();
		String page = wordParams.getPage();
		String pageSize = wordParams.getPageSize();
		String fileType = wordParams.getFileType();
		int currentPage = Integer.parseInt(page);
		int size = Integer.parseInt(pageSize);
		int startRow = (currentPage - 1) * size + 1;
		int endRow = currentPage * size;
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("cate", cate);
		paramsMap.put("regionCode", regionCode);
		paramsMap.put("date", date);
		paramsMap.put("orgCode", healthcareProviderCode);
		paramsMap.put("orgLevel", orgLevel);
		paramsMap.put("startRow", String.valueOf(startRow));
		paramsMap.put("endRow", String.valueOf(endRow));
		paramsMap.put("fileType", String.valueOf(fileType));
		List<WordInfoDTO> wordInfoDTOlist = queryWordWebPageService.getWordInfoByPage(paramsMap);
		WordInfoDTO wordInfoDTOCount = queryWordWebPageService.getWordInfoCount(paramsMap);
		int count = wordInfoDTOCount.getTotalCount();
		resultMap.put("totalCount", count);
		resultMap.put("state", 0);
		convertWordInfoListToMap(wordInfoDTOlist, resultMap);
		// 路径：
		// D:\dev\workspace\mhis_build\target\dist\mhis-hcpms\mhis-hcpms.war\wordReportFiles\G001\2015-2\0431
		// 在在数据库中查询相关文档的路径
		return resultMap;
	}

	private void convertWordInfoListToMap(List<WordInfoDTO> wordInfoDTOList, Map<String, Object> resultMap) {
		List<WordInfoDTO> tableData = new ArrayList<WordInfoDTO>();
		// 将word的数据重组
		for (WordInfoDTO dto : wordInfoDTOList) {
			WordInfoDTO tableDto = new WordInfoDTO();
			String id = dto.getId();
			String orgCode = dto.getOrgCode();
			String orgName = dto.getOrgName();
			String orgLevel = dto.getOrgLevel();
			String period = dto.getPeriod();
			if (Constants.type_2.equals(orgLevel)) {
				// 三级医院
				orgLevel = "三级医院";
			} else if (Constants.type_3.equals(orgLevel)) {
				// 二级医院
				orgLevel = "二级医院";
			} else if (Constants.type_4.equals(orgLevel)) {
				// 一级医院
				orgLevel = "一级医院";
			} else {
				// 医保报告，无等级
				orgLevel = " ";
			}

			String docDate = dto.getDocDate();
			String fileName = dto.getFileName();
			String fileType = dto.getFileType();
			tableDto.setId(id);
			tableDto.setOrgCode(orgCode);
			tableDto.setOrgName(orgName);
			tableDto.setOrgLevel(orgLevel);
			tableDto.setDocDate(docDate);
			tableDto.setFileName(fileName);
			tableDto.setFileType(fileType);
			if ("1".equals(fileType)) {
				tableDto.setWordType("医保报告");
			} else {
				tableDto.setWordType("医院报告");
			}
			tableData.add(tableDto);
		}
		resultMap.put("tableData", tableData);
	}

	/**
	 * @param request
	 * @return Map<String, Object> 查询word列表
	 */
	@RequestMapping("queryOrgListByLevel.do")
	@ResponseBody
	public Map<String, Object> queryOrgByOrgLevel(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");
		String regionCode = this.kpiRegionCodeService.getRegionCode(user.getUserId());
		String msg = "";
		if (StringUtils.isBlank(regionCode)) {
			msg = "您没有指定统筹区域,请联系管理员,";
			resultMap.put("state", 1);
			resultMap.put("msg", msg);
			return resultMap;
		}
		// 查询医院等级级联各个医院的数据
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("regionCode", regionCode);
		List<MedOrgLevelDTO> medOrgList = queryWordWebPageService.getOrgLevel(paramsMap);
		convertListToMap(medOrgList, resultMap);
		// 重组数据
		return resultMap;
	}

	private void convertListToMap(List<MedOrgLevelDTO> medOrgList, Map<String, Object> resultMap) {
		List<MedOrgLevelDTO> orgLv1 = new ArrayList<MedOrgLevelDTO>();
		List<MedOrgLevelDTO> orgLv2 = new ArrayList<MedOrgLevelDTO>();
		List<MedOrgLevelDTO> orgLv3 = new ArrayList<MedOrgLevelDTO>();
		Map<String, Object> map = new HashMap<String, Object>();
		for (MedOrgLevelDTO dto : medOrgList) {
			String orgLevel = dto.getOrgLevel();
			if (Constants.type_2.equals(orgLevel)) {
				// 三级医院
				orgLv3.add(dto);
			}
			if (Constants.type_3.equals(orgLevel)) {
				// 二级医院
				orgLv2.add(dto);
			}
			if (Constants.type_4.equals(orgLevel)) {
				// 一级医院
				orgLv1.add(dto);
			}
		}
		map.put("orgLevelAll", medOrgList);
		map.put("lv1", orgLv1);
		map.put("lv2", orgLv2);
		map.put("lv3", orgLv3);
		resultMap.put("orgLv", map);
	}

	private StringBuffer getWrodName(WordInfoDTO dto) {
		String fileType = dto.getFileType();
		String docTime = dto.getDocDate();
		String orgName = dto.getOrgName();
		docTime = docTime.replace("/", "-");
		String[] dates = docTime.split("-");
		StringBuffer wordName = new StringBuffer();
		if ("1".equals(fileType)) {
			wordName.append("厦门医保").append(dates[0]).append("年").append(dates[1]).append("月月度结算报告.rtf");
		} else if ("3".equals(fileType)) {
			wordName.append(orgName).append(dates[0]).append("年").append(dates[1]).append("月月度结算报告.rtf");
		} else {
			wordName.append("月度结算报告.rtf");
		}
		return wordName;
	}

	@RequestMapping("wordDownload.do")
	@ResponseBody
	public void downloadLocal(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");
		String id = request.getParameter("id");
		WordInfoDTO dto = this.queryWordWebPageService.getWordInfoById(id);
		String regionCode = this.kpiRegionCodeService.getRegionCode(user.getUserId());
		String orgCode = dto.getOrgCode();
		String fileName = dto.getFileName();
		String docTime = dto.getDocDate();

		logger.debug("file's attributes :{rtfReportDir:" + rtfReportDir + " regionCode:" + regionCode + " docTime:"
				+ docTime + " orgCode:" + orgCode + " fileName:" + fileName + "}");
		StringBuffer wordName = getWrodName(dto);
		StringBuffer path = new StringBuffer().append(rtfReportDir).append(regionCode).append(File.separator)
				.append(docTime).append(File.separator);
		if (StringUtils.isNotBlank(orgCode)) {
			path.append(orgCode).append(File.separator);
		}

		path.append(fileName);

		logger.debug("file exist on path:" + path);
		// 下载本地文件
		// String fileName = "Operator.docx".toString(); // 文件的默认保存名
		if (!StringUtils.isBlank(fileName)) {
			// 读到流中
			FileInputStream fis = new FileInputStream(path.toString());// 文件的存放路径
			BufferedOutputStream bos = null;
			try {
				bos = new BufferedOutputStream(response.getOutputStream());

				// 设置输出的格式
				response.reset();
				response.setContentType("application/word");
				response.addHeader("Content-Disposition",
						"attachment; filename=\"" + URLEncoder.encode(wordName.toString(), "UTF-8") + "\"");
				// 循环取出流中的数据
				byte[] b = new byte[1024];
				int len;
				while ((len = fis.read(b)) > 0)
					bos.write(b, 0, len);
				fis.close();
			} catch (IOException e) {
				logger.info("System can't find the file ...");
			} finally {
				if (fis != null)
					try {
						fis.close();
					} catch (IOException e) {
					}
				if (bos != null)
					try {
						bos.close();
					} catch (IOException e) {
					}
			}
		}
	}

	@RequestMapping("queryWordExist.do")
	@ResponseBody
	public Map<String, Object> queryWordExist(HttpServletRequest request, HttpServletResponse response) {
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");
		String msg = "";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String id = request.getParameter("id");
		WordInfoDTO dto = this.queryWordWebPageService.getWordInfoById(id);
		String regionCode = this.kpiRegionCodeService.getRegionCode(user.getUserId());
		String orgCode = dto.getOrgCode();
		String fileName = dto.getFileName();
		// 根据文件名来获取批次时间
		String docTime = dto.getDocDate();

		logger.info("file's attributes :{rtfReportDir:" + rtfReportDir + " regionCode:" + regionCode + " docTime:"
				+ docTime + " orgCode:" + orgCode + " fileName:" + fileName + "}");
		if (!StringUtils.isBlank(regionCode) || !StringUtils.isBlank(docTime) || !StringUtils.isBlank(orgCode)
				|| !StringUtils.isBlank(fileName)) {
			StringBuffer path = new StringBuffer().append(rtfReportDir).append(regionCode).append(File.separator)
					.append(docTime).append(File.separator);
			if (StringUtils.isNotBlank(orgCode)) {
				path.append(orgCode).append(File.separator);
			}
			path.append(fileName);
			// 判断指定文件夹下是否含有指定文件
			File file = new File(path.toString());
			if (file.exists()) {
				logger.info("file exist on path:" + path);
				resultMap.put("state", 0);
				return resultMap;
			}
			logger.info("file is not exist on path:" + path);
		}
		// 没有找到文件的处理
		msg = "没有找到指定文件！";
		resultMap.put("state", 1);
		resultMap.put("msg", msg);
		return resultMap;
	}

}
